<template>
  <div class="login">
    <div class="content">
      <!-- <img class="logo" src="@renderer/assets/images/logo.png" alt="" /> -->
      <el-form ref="loginRef" :rules="formRules" :model="form">
        <el-form-item label="账号" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>
        <el-form-item label=" ">
          <div style="width: 100%">
            <el-button class="login-btn" type="primary" @click="onSubmit">登录</el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { validatePassword } from '@renderer/utils/regexp.js'
import { useUserDB } from '@renderer/database/useUserDB'
import { useUserStore } from '@renderer/stores/user'
import { useRouter } from 'vue-router'
import { optionInfo, pageColorList } from '@renderer/views/option.js'
import { setStore } from '@renderer/utils/localStorage.js'
import { ElMessage } from 'element-plus'
const router = useRouter()
const userStore = useUserStore()
const { login, register, updateUserOptionInfo, addPageColor } = useUserDB()

const loginRef = ref(null)
const form = reactive({
  userName: '',
  password: ''
})
const formRules = reactive({
  userName: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ]
})
const onSubmit = () => {
  loginRef.value.validate(async (valid) => {
    if (valid) {
      // let currentUser = await getUserByName(form.userName)
      // if (isEmpty(currentUser)) {
      //   await addUser(form.userName, {
      //     ...form
      //   })
      // } else {
      //   if (currentUser.password !== form.password) {
      //     return ElMessage({ type: 'error', message: '密码错误' })
      //   }
      // }

      let currentUser = await login(form.userName)

      if (currentUser) {
        console.log('登录成功', currentUser)
        if (currentUser.profile?.password !== form.password) {
          return ElMessage({ type: 'error', message: '密码错误' })
        }
      } else {
        // 用户不存在，可以选择注册
        currentUser = await register(form.userName, { ...form })

        if (currentUser) {
          console.log('注册成功', currentUser)
        }
      }

      userStore.currentUser = { ...form }
      setStore('isLogin', 1)
      userStore.optionInfo = currentUser.optionInfo || {}
      userStore.pageColorList = currentUser.pageColorList || []

      if (isEmpty(userStore.optionInfo)) {
        userStore.optionInfo = optionInfo
        await updateUserOptionInfo(form.userName, optionInfo)
      }
      if (isEmpty(userStore.pageColorList)) {
        userStore.pageColorList = pageColorList
        await addPageColor(form.userName, pageColorList)
      }

      console.log(userStore.optionInfo, optionInfo)

      router.push('/home')
    } else {
      console.log('error submit!!')
      return false
    }
  })
}

/**
 * 检查值是否为空
 * @param {*} value - 要检查的值
 * @returns {boolean} - 如果为空则返回 true，否则返回 false
 */
function isEmpty(value) {
  // 处理 null 和 undefined
  if (value === null || value === undefined) {
    return true
  }

  // 处理字符串
  if (typeof value === 'string') {
    return value.trim().length === 0
  }

  // 处理数组
  if (Array.isArray(value)) {
    return value.length === 0
  }

  // 处理对象
  if (typeof value === 'object') {
    return Object.keys(value).length === 0
  }

  // 处理数字、布尔值等其他类型
  return false
}
</script>

<style lang="scss" scoped>
.login {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  .content {
    width: 300px;
    //   height: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    .logo {
      width: 200px;
      height: auto;
    }
  }
  .login-btn {
    margin-left: 28px;
    width: 191px;
  }
}
</style>
